<?php

namespace Home\Controller;

use Utuo\WechatActivityController;
use Home\Logic\DistributionShopRedPacketLogic;

class RedPaperController extends WechatActivityController {
	// activity config
	private $activity;
	
	// host info
	private $hostInfo;
	
	// prize info
	// 中奖等级，与前端一致： [20, -10, 30, -5, 10, -20, 5, 0];
	private $prizeLevel = array (
			20,
			-10,
			30,
			-5,
			10,
			-20,
			5,
			0 
	);
	
	private $positiveIndexes = array(0,2,4,6);
	private $negativeIndexes = array(1,3,5,7);
	
	// init
	public function _initialize() {
		layout('RedPaper/layout');
	}
	
	// 活动主页
	public function indexAction() {
		// 活动信息
		$this->activity = M('WechatActivityRedPaper')->find($this->aid);
		
		// 活动分享地址
		$this->activity['shareUrl'] = $this->getFullUrl(array (
				'cid' => $this->cid,
				'aid' => $this->aid,
				'fid' => $this->userInfo['id'] 
		));
		
		// 当前用户发起活动信息
		$this->hostInfo = M('WechatActivityRedPaperHost')->where(array (
				'cid' => $this->cid,
				'aid' => $this->aid,
				'uid' => $this->userInfo['id'] 
		))->find();
		
		// 中奖登记信息
		$registerInfo = null;
		
		if (!empty($this->hostInfo)) {
			$this->hostInfo['diff'] = $this->activity['prizePrice'] - $this->hostInfo['money'];
			// 如果基金已经完成，查看登记情况
			if ($this->hostInfo['diff'] <= 0) {
				$registerInfo = M('WechatActivityRedPaperRegister')->where(array (
						'cid' => $this->cid,
						'aid' => $this->aid,
						'uid' => $this->userInfo['id'],
						'hid' => $this->hostInfo['id'] 
				))->find();
			}
		}
		
		// 好友抽奖地址
		$this->activity['playUrl'] = $this->getFullUrl(array (
				'cid' => $this->cid,
				'aid' => $this->aid,
				'fid' => $this->userInfo['id'],
				'hid' => $this->hostInfo['id'] 
		), 'play');
		
		// 视图
		$this->assign('registerInfo',$registerInfo);
		$this->assign('userInfo', $this->userInfo);
		$this->assign('activity', $this->activity);
		$this->assign('hostInfo', $this->hostInfo);
		$this->display();
	}
	
	// 抽奖页面
	public function playAction() {
		// 发起活动信息
		$hid = I('hid', 0, 'intval');
		
		// 查看我发起的活动信息
		$myHostId = M('WechatActivityRedPaperHost')->where(array (
				'cid' => $this->cid,
				'aid' => $this->aid,
				'uid' => $this->userInfo['id'] 
		))->getField('id');
		empty($myHostId) or $this->userInfo['hid'] = $myHostId;
		
		// 活动信息
		$this->activity = M('WechatActivityRedPaper')->find($this->aid);
		$this->activity && $this->activity['shareUrl'] = $this->getFullUrl(array (
				'cid' => $this->cid,
				'aid' => $this->aid,
				'fid' => $this->userInfo['id'] 
		), 'index');
		
		// 当前用户发起活动信息
		$this->hostInfo = M('WechatActivityRedPaperHost h')->join('LEFT JOIN __WECHAT_ACTIVITY_USER__ u ON h.uid=u.id')->field("h.*, u.nickname")->where(array (
				'h.id' => $hid 
		))->find();
		
		// 今天已经抽奖次数
		$timesPlayed = M('WechatActivityRedPaperPlay')->where(array (
				'cid' => $this->cid,
				'aid' => $this->aid,
				'uid' => $this->userInfo['id'],
				'hid' => $hid,
				'date' => date('Ymd') 
		))->count();
		
		$this->hostInfo['timesPlayed'] = intval($timesPlayed);
		
		// 视图
		$this->assign('userInfo', $this->userInfo);
		$this->assign('activity', $this->activity);
		$this->assign('hostInfo', $this->hostInfo);
		$this->display();
	}
	
	// 抽奖请求，ajax请求，不经过跳转
	public function turnAction() {
		$uid = I('uid', 0, 'intval') or $this->ajaxError("请求参数错误，请重试！");
		$hid = I('hid', 0, 'intval') or $this->ajaxError('请求参数错误，请重试！');
		
		$this->hostInfo = M('WechatActivityRedPaperHost')->find($hid);
		$this->hostInfo['uid'] == $uid && $this->ajaxError("自己不能给自己抽奖哦~");
		
		// 活动信息
		$this->activity = M('WechatActivityRedPaper')->where(array (
				'cid' => $this->cid,
				'id' => $this->aid 
		))->find();
		empty($this->activity) && $this->ajaxError('活动信息错误，请重试！');
		
		// 判断是否需要关注
		if ($this->activity['isMustSubscribe']){
		    if (!$this->userInfo['subscribe']){
		        $this->ajaxError('想要帮朋友抽红包，先关注我们哦~');
		    }
		}
		
		// 判断基金总额，如果大于奖品价钱，则不允许再抽奖
		$this->hostInfo['money'] >= $this->activity['prizePrice'] && $this->ajaxError("金额已经足够，不需要再抽奖了~");
		
		// 中奖基本数据
		$data = array (
				'cid' => $this->cid,
				'aid' => $this->aid,
				'uid' => $uid,
				'hid' => $hid,
				'date' => date('Ymd') 
		);
		
		// 今日已经抽奖次数
		$timesPlayed = M('WechatActivityRedPaperPlay')->where($data)->count();
		$timesPerDay = $this->activity['timesPerDay'];
		
		$timesPlayed >= $timesPerDay && $this->ajaxError('您今天已经帮过ta啦，明天再帮吧！');
		
// 		if ($this->cid==1){
		    if ($this->activity['difficultMoney']>0 && $this->hostInfo['money']>=$this->activity['difficultMoney']){
		        // 产生抽奖数据
		        $prizeIndex = $this->negativeIndexes[array_rand($this->negativeIndexes)];
		    } else {
		        $prizeIndex = rand(0, 7);
		    }
		    $prizeMoney = $this->prizeLevel[$prizeIndex];
// 		    $this->ajaxError($this->activity['difficultMoney'].'/'.$this->hostInfo['money'].'/'.$prizeIndex.'/'.$prizeMoney);
		    
// 		} else {
		
//     		// 产生抽奖数据
//     		$prizeIndex = rand(0, 7);
//     		$prizeMoney = $this->prizeLevel[$prizeIndex];
		
// 		}
		
		// 添加抽奖记录
		$data['money'] = $prizeMoney;
		if (M('WechatActivityRedPaperPlay')->add($data)) {
			// 避免出现负数
			$money = max($this->hostInfo['money'] + $prizeMoney, 0);
			M('WechatActivityRedPaperHost')->where(array (
					'id' => $hid 
			))->setField("money", $money);
			$this->ajaxSuccess('抽奖成功', array (
					'index' => $prizeIndex,
					'money' => $prizeMoney,
					'times' => $timesPerDay - $timesPlayed - 1 
			));
		}
		
		$this->ajaxError('抽奖失败，请重试~');
	}
	
	// 登录中奖用户
	public function registerAction() {
		$m = M('WechatActivityRedPaperRegister');
		$uid = I('uid', 0, 'intval');
		
		// 检查是否已经登记
		$count = $m->where(array (
				'cid' => $this->cid,
				'aid' => $this->aid,
				'uid' => $uid,
				'hid' => I('hid', 0, 'intval') 
		))->count();
		$count === false && $this->ajaxError('网络错误，请重试！(001)');
		$count > 0 && $this->ajaxError('您已经登记过了~');
		
		// 活动信息
		$activity = M('WechatActivityRedPaper')->where(array (
				'cid' => $this->cid,
				'id' => $this->aid 
		))->field("prizeCount,prizePrice,prizeFulfil")->find();
		
		empty($activity) && $this->ajaxError('网络错误，请重试！(002)');
		
		// 已经登记人数
		$registerCount = $m->where(array (
				'cid' => $this->cid,
				'aid' => $this->aid 
		))->count();
		$registerCount === false && $this->ajaxError('网络错误，请重试！(003)');
		
		// 检查登记人数是否已经超过活动限制人数
		($registerCount >= $activity['prizeCount']) && $this->ajaxError('很遗憾，登记人数已经超过奖品数量~');
		
		C("TOKEN_ON", false);
		
		if ($m->create()) {
			$m->createTime = time();
			$tag = "WechatActivityRedPaper-".$this->aid;
			$userId = M('WechatUser')->where(array('cid'=>$this->cid,'openId'=>I('oid')))->getField("id");
			// 添加红包
			$packetData = DistributionShopRedPacketLogic::newRedPacket($this->cid, $userId, $activity['prizePrice'], $activity['prizeFulfil'], $tag, 0);
			$packetId = DistributionShopRedPacketLogic::addRedPacket($packetData);
			// 如果创建红包失败
			empty($packetId) && $this->ajaxError('网络错误，请重试一次吧(003)');
			
			// 创建红包成功，登记领取红包用户信息
			$m->redPacketId = $packetId;
			if ($m->add()) {
				$this->ajaxSuccess('登记成功，红包已经发送到您的账户，请登录个人中心查看~');
			} else {
			    // 这里有个问题，如果登记用户领取红包信息失败，有可能会产生多个红包，所以登记信息失败，也返回成功。
				$this->ajaxSuccess('红包已经发送到您的账户，请登录个人中心查看~');
			}
		} else {
			$this->ajaxError('提交数据错误，请检查重试~' . $m->getError());
		}
	}
	
	// 获取基金明细，ajax请求
	public function detailAction() {
		$hid = I('hid', 0, 'intval') or $this->ajaxError("参数错误");
		
		$condition = array (
				'p.cid' => $this->cid,
				'p.aid' => $this->aid,
				'p.hid' => $hid 
		);
		
		$lists = M('WechatActivityRedPaperPlay p')->join('LEFT JOIN __WECHAT_ACTIVITY_USER__ u ON p.uid=u.id')->where($condition)->field("p.*, u.nickname")->select();
		if ($lists === false) {
			$this->ajaxError('网络错误，请重试~');
		} else {
			$this->ajaxSuccess('获取数据成功！', $lists);
		}
	}
	
	// 发起活动，ajax请求，不经过跳转
	public function hostAction() {
		$uid = I('uid', 0, 'intval');
		$data = array (
				'cid' => $this->cid,
				'aid' => $this->aid,
				'uid' => $uid 
		);
		$this->hostInfo = M('WechatActivityRedPaperHost')->where($data)->find();
		if ($this->hostInfo) {
			$this->ajaxError("每个用户只能发起一次活动哦");
		}
		$defaultMoney = M('WechatActivityRedPaper')->where("id=%d", $this->aid)->getField('defaultMoney');
		$data['money'] = $defaultMoney;
		$hostId = M('WechatActivityRedPaperHost')->add($data);
		if ($hostId) {
			$this->ajaxSuccess("发起活动成功", array (
					'hostId' => $hostId 
			));
		} else {
			$this->ajaxError("发起活动失败，请重新试试吧！");
		}
	}
}